<template>
  <div class="dashboard">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>数据概览</h1>
      <p>欢迎回来，{{ authStore.user?.fullName || authStore.user?.username }}！</p>
    </div>

    <!-- 核心数据概览 -->
    <div class="overview-cards">
      <el-row :gutter="20">
        <!-- 今日新增用户 -->
        <el-col :xs="24" :sm="12" :md="6">
          <div class="stat-card">
            <div class="stat-icon user">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ overview?.today.newUsers || 0 }}</div>
              <div class="stat-label">今日新增用户</div>
              <div class="stat-compare">
                昨日: {{ overview?.yesterday.newUsers || 0 }}
              </div>
            </div>
          </div>
        </el-col>

        <!-- 今日订单数 -->
        <el-col :xs="24" :sm="12" :md="6">
          <div class="stat-card">
            <div class="stat-icon order">
              <el-icon><ShoppingCart /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ overview?.today.orders || 0 }}</div>
              <div class="stat-label">今日订单数</div>
              <div class="stat-compare">
                昨日: {{ overview?.yesterday.orders || 0 }}
              </div>
            </div>
          </div>
        </el-col>

        <!-- 今日销售额 -->
        <el-col :xs="24" :sm="12" :md="6">
          <div class="stat-card">
            <div class="stat-icon sales">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">¥{{ formatMoney(overview?.today.sales || 0) }}</div>
              <div class="stat-label">今日销售额</div>
              <div class="stat-compare">
                昨日: ¥{{ formatMoney(overview?.yesterday.sales || 0) }}
              </div>
            </div>
          </div>
        </el-col>

        <!-- 累计销售额 -->
        <el-col :xs="24" :sm="12" :md="6">
          <div class="stat-card">
            <div class="stat-icon total">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">¥{{ formatMoney(overview?.total.sales || 0) }}</div>
              <div class="stat-label">累计销售额</div>
              <div class="stat-compare">
                总订单: {{ overview?.total.orders || 0 }}
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <el-row :gutter="20">
      <!-- 左侧内容 -->
      <el-col :xs="24" :lg="16">
        <!-- 销售趋势图 -->
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>销售趋势</span>
              <el-button-group size="small">
                <el-button
                  :type="trendDays === 7 ? 'primary' : ''"
                  @click="changeTrendDays(7)"
                >
                  7天
                </el-button>
                <el-button
                  :type="trendDays === 30 ? 'primary' : ''"
                  @click="changeTrendDays(30)"
                >
                  30天
                </el-button>
              </el-button-group>
            </div>
          </template>

          <div class="chart-container">
            <div v-if="loading" class="chart-loading">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span>加载中...</span>
            </div>
            <div v-else-if="!salesTrend.length" class="chart-empty">
              <el-icon><DocumentDelete /></el-icon>
              <span>暂无数据</span>
            </div>
            <div v-else class="chart-content">
              <!-- 这里可以集成ECharts图表 -->
              <div class="simple-chart">
                <div
                  v-for="(item, index) in salesTrend"
                  :key="index"
                  class="chart-bar"
                  :style="{ height: `${(item.salesAmount / maxSales) * 100}%` }"
                  :title="`${item.date}: ¥${formatMoney(item.salesAmount)}`"
                >
                  <div class="bar-value">¥{{ formatMoney(item.salesAmount) }}</div>
                </div>
              </div>
              <div class="chart-labels">
                <div
                  v-for="(item, index) in salesTrend"
                  :key="index"
                  class="chart-label"
                >
                  {{ formatDate(item.date) }}
                </div>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 快捷入口 -->
        <el-card class="quick-actions-card" shadow="hover">
          <template #header>
            <span>快捷操作</span>
          </template>

          <div class="quick-actions">
            <div
              v-for="action in quickActions"
              :key="action.id"
              class="quick-action-item"
              @click="handleQuickAction(action)"
            >
              <div class="action-icon">
                <el-icon>
                  <component :is="getIconComponent(action.icon)" />
                </el-icon>
              </div>
              <div class="action-content">
                <div class="action-title">{{ action.title }}</div>
                <div class="action-desc">{{ action.description }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧内容 -->
      <el-col :xs="24" :lg="8">
        <!-- 待办事项 -->
        <el-card class="pending-tasks-card" shadow="hover">
          <template #header>
            <span>待办事项</span>
          </template>

          <div class="pending-tasks">
            <!-- 库存预警 -->
            <div class="task-item" @click="goToLowStock">
              <div class="task-icon warning">
                <el-icon><Warning /></el-icon>
              </div>
              <div class="task-content">
                <div class="task-title">库存预警</div>
                <div class="task-count">{{ pendingTasks?.lowStock.count || 0 }} 个商品</div>
              </div>
              <el-icon class="task-arrow"><ArrowRight /></el-icon>
            </div>
          </div>
        </el-card>

        <!-- 库存预警商品列表 -->
        <el-card v-if="pendingTasks?.lowStock.products.length" class="low-stock-card" shadow="hover">
          <template #header>
            <span>库存不足商品</span>
          </template>

          <div class="low-stock-list">
            <div
              v-for="product in pendingTasks.lowStock.products.slice(0, 5)"
              :key="product.id"
              class="low-stock-item"
            >
              <el-image
                :src="product.main_image_url"
                class="product-image"
                fit="cover"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <div class="product-info">
                <div class="product-name">{{ product.name }}</div>
                <div class="product-stock">库存: {{ product.stock_quantity }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  User,
  ShoppingCart,
  Money,
  TrendCharts,
  ArrowRight,
  Warning,
  Picture,
  Plus,
  Service,
  DataAnalysis,
  Loading,
  DocumentDelete
} from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { useDashboardStore } from '@/stores/dashboard'

const router = useRouter()
const authStore = useAuthStore()
const dashboardStore = useDashboardStore()

// 趋势图天数
const trendDays = ref(7)

// 计算属性
const overview = computed(() => dashboardStore.overview)
const pendingTasks = computed(() => dashboardStore.pendingTasks)
const salesTrend = computed(() => dashboardStore.salesTrend)
const quickActions = computed(() => dashboardStore.quickActions)
const loading = computed(() => dashboardStore.loading)

// 计算最大销售额用于图表比例
const maxSales = computed(() => {
  if (!salesTrend.value.length) return 1
  return Math.max(...salesTrend.value.map(item => item.salesAmount))
})

// 格式化金额
const formatMoney = (amount: number) => {
  return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2 })
}

// 格式化日期
const formatDate = (dateStr: string) => {
  const date = new Date(dateStr)
  return `${date.getMonth() + 1}/${date.getDate()}`
}

// 获取图标组件
const getIconComponent = (iconName: string) => {
  const iconMap: Record<string, any> = {
    'plus': Plus,
    'shopping-cart': ShoppingCart,
    'users': User,
    'alert-triangle': Warning,
    'bar-chart': DataAnalysis,
    'headphones': Service
  }
  return iconMap[iconName] || Plus
}

// 改变趋势图天数
const changeTrendDays = async (days: number) => {
  trendDays.value = days
  await dashboardStore.fetchSalesTrend(days)
}

// 处理快捷操作
const handleQuickAction = (action: any) => {
  if (action.route) {
    router.push(action.route)
  } else {
    ElMessage.info(`${action.title} 功能开发中`)
  }
}


// 跳转到库存预警页面
const goToLowStock = () => {
  router.push('/products?filter=low-stock')
}

// 组件挂载时加载数据
onMounted(async () => {
  await dashboardStore.refreshAll()
})
</script>

<style scoped>
.dashboard {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-header p {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.overview-cards {
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 16px;
  height: 120px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stat-icon.user { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.stat-icon.order { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
.stat-icon.sales { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
.stat-icon.total { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.stat-compare {
  font-size: 12px;
  color: #909399;
}

.chart-card,
.quick-actions-card,
.pending-tasks-card,
.low-stock-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 300px;
  position: relative;
}

.chart-loading,
.chart-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  gap: 8px;
}

.chart-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.simple-chart {
  flex: 1;
  display: flex;
  align-items: end;
  justify-content: space-around;
  padding: 20px 0;
  gap: 8px;
}

.chart-bar {
  flex: 1;
  background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
  border-radius: 4px 4px 0 0;
  min-height: 20px;
  position: relative;
  cursor: pointer;
  transition: all 0.3s;
}

.chart-bar:hover {
  opacity: 0.8;
  transform: translateY(-2px);
}

.bar-value {
  position: absolute;
  top: -25px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 12px;
  color: #606266;
  white-space: nowrap;
  opacity: 0;
  transition: opacity 0.3s;
}

.chart-bar:hover .bar-value {
  opacity: 1;
}

.chart-labels {
  display: flex;
  justify-content: space-around;
  padding: 10px 0;
  border-top: 1px solid #ebeef5;
  gap: 8px;
}

.chart-label {
  flex: 1;
  text-align: center;
  font-size: 12px;
  color: #909399;
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.quick-action-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.quick-action-item:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.action-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
}

.action-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.action-desc {
  font-size: 12px;
  color: #909399;
}

.pending-tasks {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.task-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.task-item:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.task-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
}

.task-icon.warning {
  background: #e6a23c;
}

.task-content {
  flex: 1;
}

.task-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.task-count {
  font-size: 12px;
  color: #909399;
}

.task-arrow {
  color: #c0c4cc;
}

.low-stock-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.low-stock-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
}

.product-image {
  width: 40px;
  height: 40px;
  border-radius: 4px;
}

.image-slot {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 14px;
  color: #303133;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-stock {
  font-size: 12px;
  color: #e6a23c;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .quick-actions {
    grid-template-columns: 1fr;
  }

  .stat-card {
    height: auto;
    min-height: 100px;
  }

  .chart-container {
    height: 250px;
  }
}
</style>
